<?php

namespace App\Models\Api;

use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Site;
use JMessage\IM\User as IMUser;
use JMessage\JMessage;

class CompanyUser extends Authenticatable
{
    //
    protected $table = 'company_users';
    public $primaryKey = 'uid';

    const CREATED_AT = 'regtime';
    const UPDATED_AT = 'updatetime';

    protected $dates = ['viptime'];

    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     * 隐藏字段
     * @var array
     */
    protected $hidden = ['password', 'regip', 'last_login_ip', 'remember_token',
        'regtime', 'updatetime', 'last_login_time', 'company_basic', 'device_token',
        'pwd_hash', 'last_service_time', 'surpris_visit_time', 'email_id', 'crm_uid',
        'mobile_id', 'qqopenid', 'wechatopenid', 'wechatmpopenid', 'wechatunionid',];

    protected $casts = [
        'vip_resume_number' => 'string',
        'vip_integral' => 'string',
        'resume_number' => 'string',
        'integral' => 'string',
        'vip_post_number' => 'string',
    ];

    public function company_basic()
    {
        return $this->hasOne(CompanyBasic::class, 'uid', 'uid')
            ->select(['id', 'uid', 'logo', 'industry', 'cert_status']);
    }

    public function getComIdAttribute()
    {
        return $this->company_basic ? $this->company_basic->id : '';
    }

    public function getComEidAttribute()
    {
        return $this->company_basic ? idEncryption($this->company_basic->id) : '';
    }

    public function getLogoAttribute()
    {
        return $this->company_basic ? $this->company_basic->logo : '';
    }

    public function getIsVipAttribute()
    {
        //当前时间小于viptime,是vip
        if (is_null($this->viptime)) {
            return 0;
        }
        return intval(Carbon::now()->lt($this->viptime));
    }

    public function getIndustryAttribute()
    {
        return $this->company_basic ? $this->company_basic->industry : '';
    }

    public function getIndustryNameAttribute()
    {
        return $this->company_basic ? $this->company_basic->industry_name : '';
    }

    public function getCertStatusAttribute()
    {
        return $this->company_basic ? $this->company_basic->cert_status : '0';
    }

    /** 判断积分是否足够
     * @param int $value
     * @return bool
     */
    public function integralEnough($value = 0)
    {
        if ($this->is_vip) {//是会员
            //判断会员积分+普通积分是否大于消耗数
            return $this->vip_integral + $this->integral >= $value;
        }
        //不是会员,判断普通积分是否大于消耗数
        return $this->integral >= $value;
    }

    /** 扣除积分
     * @param int $value
     * @return bool
     */
    public function integralDeduct($value = 0)
    {
        if ($this->is_vip) {//是会员
            if ($this->vip_integral != 0 && $this->vip_integral >= $value) {//会员积分足够
                $this->vip_integral -= $value;
                $this->save();
                return true;
            }

            $total = $this->vip_integral + $this->integral;
            if ($total != 0 && $total >= $value) {//会员积分+普通积分足够
                $this->integral = $this->integral - ($value - $this->vip_integral);
                $this->vip_integral = 0;
                $this->save();
                return true;
            }
            return false;
        }

        if ($this->integral != 0 && $this->integral >= $value) {//普通积分足够
            $this->integral -= $value;
            $this->save();
            return true;
        }
        return false;
    }

    /** 判断简历数是否足够
     * @param int $value
     * @return bool
     */
    public function resumeEnough($value = 0)
    {
        if ($this->is_vip) {//是会员
            //判断会员简历数+普通简历数是否大于消耗数
            return ($this->vip_resume_number + $this->resume_number) >= $value;
        }
        //不是会员,判断普通简历数是否大于消耗数
        return $this->resume_number >= $value;
    }

    /** 扣除简历数
     * @param int $value
     * @return bool
     */
    public function resumeDeduct($value = 0)
    {
        if ($this->is_vip) {//是会员
            if ($this->vip_resume_number != 0 && $this->vip_resume_number >= $value) {//会员简历数足够
                $this->vip_resume_number -= $value;
                $this->save();
                return true;
            }
            $total = $this->vip_resume_number + $this->resume_number;
            if ($total != 0 && $total >= $value) {//会员简历数+普通简历数足够
                $this->resume_number = $this->resume_number - ($value - $this->vip_resume_number);
                $this->vip_resume_number = 0;
                $this->save();
                return true;
            }
            return false;
        }

        if ($this->resume_number != 0 && $this->resume_number >= $value) {//普通简历数足够
            $this->resume_number -= $value;
            $this->save();
            return true;
        }
        return false;
    }

    /** 获取聊天密码
     * @return mixed
     */
    public function getChatPwdAttribute()
    {
        $where = [
            'uid' => $this->uid,
            'type' => 'chat_pwd',
        ];
        $p = \DB::table('company_bind')->where($where)->first();

        if (!empty($p)) {
            return $p->keyid;
        }

        //注册聊天账号
        $appKey = Site::get('company_app_key');
        $masterSecret = Site::get('company_master_secret');

        $username = 'company_' . $this->uid;
        $jm = new JMessage($appKey, $masterSecret);
        $user = new IMUser($jm);
        $pwd = str_random(20);
        $response = $user->register($username, $pwd);

        //注册失败
        if ($response['http_code'] < 200 || $response['http_code'] > 299) {
            if (array_key_exists('error', $response['body'][0])) {
                if ($response['body'][0]['error']['code'] == 899001) {//已经注册过了
                    $pwd = $username;
                } else {
                    return '';
                }
            } else {
                return '';
            }
        }

        //保存密码
        $create = [
            'uid' => $this->uid,
            'type' => 'chat_pwd',
            'keyid' => $pwd,
            'created_at' => Carbon::now()
        ];
        \DB::table('company_bind')->insert($create);

        //给聊天账户赋值信息
        if (!empty($this->company_basic)) {
            $user->update($username, [
                'nickname' => $this->company_basic->company_name,
                'address' => $this->company_basic->logo,
                'signature' => $this->company_basic->id,
                'region' => idEncryption($this->company_basic->id)
            ]);
        }
        return $pwd;
    }
}
